package com.sohoo.comm.modbus;

import com.serotonin.modbus4j.BasicProcessImage;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.ip.listener.TcpListener;
import com.serotonin.modbus4j.ip.tcp.TcpSlave;
import com.serotonin.modbus4j.msg.ModbusResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;


public class ModBusDemo {

	public static void main(String[] args) throws ModbusInitException, Exception {
		IpParameters params = new IpParameters();
		params.setHost("192.168.1.249");
		params.setPort(7001);
		params.setEncapsulated(true);
//		ModbusSlaveSet tcpSlave = new ModbusFactory().createTcpSlave(true);
//		tcpSlave.start();
//		TcpSlave slave = new  TcpSlave(7001, true);
//		slave.addProcessImage(new BasicProcessImage(0));
//		slave.start();
		TcpListener tcpListener = (TcpListener) new ModbusFactory().createTcpListener(params);
		tcpListener.setTimeout(2000);
		tcpListener.setRetries(5);
		tcpListener.init();
		ReadHoldingRegistersRequest request;
		try {
			request = new ReadHoldingRegistersRequest(0, 1, 7);
			ModbusResponse response = tcpListener.send(request);
			System.out.println(response);
		} catch (ModbusTransportException e) {
			e.printStackTrace();
		}
	}

}
